package com.emperor.core.logic;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public abstract class BizModelBase extends DataModelBase implements BizModel {

	public abstract List<String> getFieldNames();

	public BizModel setValues(Map<String, Object> params) {
		return setValues(null, params);
	}

	public BizModel setValues(String prefix, Map<String, Object> params) {
		List<String> fieldNames = this.getFieldNames();

		if (fieldNames != null && !fieldNames.isEmpty()) {
			try {
				for (Iterator<String> iter = fieldNames.iterator(); iter
						.hasNext();) {
					String fieldName = iter.next();
					Object param = null;
					if (prefix != null) {
						param = params.get(prefix + "_" + fieldName);
					} else {
						param = params.get(fieldName);
					}
					
					fieldName = toUpperCase(fieldName);
					Method method = this.getClass().getMethod(
							"set" + fieldName, Object.class);
					method.invoke(this, param);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return this;
	}

	public Map<String, Object> getValues() {
		Map<String, Object> values = new HashMap<String, Object>();

		List<String> fieldNames = this.getFieldNames();

		if (fieldNames != null && !fieldNames.isEmpty()) {
			try {
				Object param = null;
				String fieldName = "", upperName = "";
				for (Iterator<String> iter = fieldNames.iterator(); iter
						.hasNext();) {
					fieldName = iter.next();
					upperName = toUpperCase(fieldName);
					Method method = this.getClass().getMethod(
							"get" + upperName, null);
					param = method.invoke(this, null);
					values.put(fieldName, param);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return values;
	}

	public String toUpperCase(String fieldName) {
		if (fieldName != null && fieldName.length() > 1) {
			String x = fieldName.substring(0, 1);
			String y = fieldName.substring(1, fieldName.length());
			fieldName = x.toUpperCase() + y;
		}
		return fieldName;
	}

	public String toLowerCase(String fieldName) {
		if (fieldName != null && fieldName.length() > 1) {
			String x = fieldName.substring(0, 1);
			String y = fieldName.substring(1, fieldName.length());
			fieldName = x.toLowerCase() + y;
		}
		return fieldName;
	}
}
